<template>
  <div class="treeBox">
    <el-row style="padding: 8px">
      <el-col :span="24">
        <el-button style="float:right;" @click="refsh" type="primary" size="medium">刷新</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top:5px">
      <vxe-table
        ref="mytable"
        :resizable=true
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-id="id"
        :max-height="heightY"
        highlight-current-row
        :height="heightY"
        :indent="indentNumber"
        border
        :tree-config="{children: 'children', hasChild: 'isParent',lazy:true,loadMethod:load}"
      >
        <vxe-column
          field="name"
          title="目录名称"
          sortable
          width="700"
          tree-node
        />
        <vxe-column
          field="content3"
          title="序号"
          sortable
        />
        <vxe-column
          title="操作"
          align="center"
          header-align="center"
          width="600"
        >
          <template slot-scope="scope">
            <el-button
              plain
              type="primary"
              :disabled="selectAssessState != 1"
              @click="addTree(scope.row)"
            >
              添加下级
            </el-button>
            <el-button
              type="primary"
              plain
              :disabled="selectAssessState != 1"
              @click="hanldupdateSort(scope.row)"
            >
              调整下级排序
            </el-button>
            <el-button
              type="primary"
              plain
              :disabled="selectAssessState != 1"
              @click="updateTree(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              plain
              :disabled="selectAssessState != 1"
              @click="deleteTreeDataById(scope.row)"
            >
              删除
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <div
        class="row"
        style="width: 100%; float: left; text-align: center; margin-top: 5px"
      />
    </el-row>
    <!-- 弹框 -->
    <el-dialog
      :title="form.treeTitle"
      :fullscreen="dialogFullscree"
      :visible.sync="dialogVisible"
      width="40%"
      class="showDialogClass"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="190px"
      >
        <el-form-item label="选择目录">
          <div  @click="openDrawer">
            <el-input
              placeholder="单击此处选择发布目录"
              style="max-width: 70%"
              readonly
              v-model="treeIndexDesc"
            />
          </div>
            <el-input
              v-show="false"
              v-model="treeIndex"
            />
        </el-form-item>
        <el-form-item :label="form.treeLabel">
          <el-input
            :disabled="false"
            v-model="form.name"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model.number="form.sort"
            :min="1"
            :max="999"
            label="只能是数字"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="onSubmit"
        >
         保存
        </el-button>
        <el-button @click="handleClose">
          取消
        </el-button>
      </span>
    </el-dialog>
    <updateSort
       ref="updateSortRef"
       v-if="updateSortFlag"
       :sub-tree-data="subTreeData"
       :cascader-list="cascaderList"
       @refresh="getDataList"
       ></updateSort>
    <DiretorySelect ref="diretorySelect" @onChange="handleDiretorySelect"/>

  </div>
</template>

  <script>
  import { getTreeDataList, save, update, deleteTree } from "@/api/knowledge/diretory";
  import store from "@/store";
  import updateSort from "./updateSort";
  import DiretorySelect from '../components/diretorySelect.vue'

  export default {
    name: `templateName`,
    components:{updateSort, DiretorySelect},
    data () {
      return {
        tableData: [],
        indentNumber: 24,
        heightY: `${window.innerHeight - 150}px`,
        dialogVisible: false,
        dialogFullscree: false,
        selectAssessState: 1,
        // 表单变量
        form: {
          treeLabel: ``,
          treeTitle: ``,
          id: null,
          name: ``,
          sort: null,
          state: ``,
        },
        addRow: ``,
        updateRow: ``,
        fileBussinessTypeCode: `111`,
        maps: new Map(),
        updateSortFlag:false,
        subTreeData: [], // 子节点数据
        cascadrValue:[],
        treeIndex:"",
        cascaderList:[],
        treeIndexDesc:"",
      };
    },
    created () {
      this.getDataList();
      this.init();
    },
    watch:{
    },
    //方法集合
    methods: {
      init(){
        this.updateSortFlag = true;
      },

      // 樹的選擇
      handleDiretorySelect(data) {
        this.treeIndexDesc = data.name
        this.treeIndex = data.id;
      },
      load({ row }) {
        return new Promise((resolve) => {
          setTimeout(() => {
            const params = {
              userId: store.getters.user_id.toString(),
              token: store.getters.token.toString(),
              userName: store.getters.userName.toString(),
              data: {
                fileBussinessTypeCode: this.fileBussinessTypeCode,
                fileDiretoryId: row.id,
              },
            };
            getTreeDataList(params).then((data) => {
              if (data.result === true) {
                // 新增：将数据存储到 maps 属性中
                this.maps.set(row.id, { row, children: data.resultdata.data });
                resolve(data.resultdata.data);
              } else {
                this.$message({
                  type: `warning`,
                  message: `获取信息出错`,
                });
              }
            });
          }, 1000);
        });
      },
      getDataList () {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          data: {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryId: null,
          },
        };
        getTreeDataList(params).then((data) => {
          if (data.result === true) {
            this.tableData = data.resultdata.data;
          }
          else {
            this.$message({
              type: `warning`,
              message: `获取信息出错`,
            });
          }
        });
      },
      refsh(){
        this.$nextTick(() => {
          this.tableData = [];
        })
        this.getDataList();
      },
      openDrawer () {
        this.$refs.diretorySelect.open()
      },
      // 调整下级排序
      hanldupdateSort(data) {
        this.updateSortFlag = true;
        this.cascaderList = this.tableData
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          data: {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryId: data.id,
          },
        };
        getTreeDataList(params).then((res) => {
          if (res.result === true) {
            this.subTreeData = res.resultdata.data;
            this.$nextTick(() => {
              this.$refs.updateSortRef.init(data);
            });
          } else {
            this.$message({
              type: "warning",
              message: "获取信息出错",
            });
          }
        });
      },
      deleteTreeDataById (row) {
        this.$confirm(`是否确认删除?`, `提示`, {
          confirmButtonText: `确定`,
          cancelButtonText: `取消`,
          type: `warning`,
        }).then(() => {
          const params = {
            'userId': store.getters.user_id.toString(),
            'token': store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              fileDiretoryId: row.id,
              fileBussinessTypeCode: this.fileBussinessTypeCode,
            },
          }
          deleteTree(params).then((data) => {
            if (data.result === true) {
              this.$message({
                type: `success`,
                message: `删除成功`,
              })
            }
          })
        })
          .catch((err) => {
            this.$message({
              type: `info`,
              message: `删除已取消`,
            })
          })
      },
      getAllParents(id) {
        let list = this.tableData
        function getParentTree(id, tree) {
          let arr = [];
          for (let i = 0; i < tree.length; i++) {
            let item = tree[i];
            arr = [];
            arr.push(item);
            if (id == item.id) {
              return arr;
            } else {
              if (item.children && item.children.length > 0) {
                arr = arr.concat(getParentTree(id, item.children ? item.children : []));
                if (arr.map((item2) => (item2 ? item2.id : "")).includes(id)) {
                  return arr;
                }
              }
            }
          }
        }
        return getParentTree(id, list)
      },
      //新增下级按钮
      addTree (row) {
        this.addRow = row;
        this.dialogVisible = true;
        this.form.treeTitle = `新增下级目录`
        this.form.treeLabel = `新增目录名称`
        this.form.state=`add`;
        this.form.name=``;
        this.cascadrValue = [];
        this.treeIndexDesc = ''
        this.treeIndex = '';
        if(row.pid === '0') {
          this.cascadrValue = [row.id]
        } else {
          let arr = this.getAllParents(row.id)
          this.cascadrValue = arr.map(e => e.id)
        }
      },
      // 修改按钮
      updateTree (row) {
        this.updateRow = row;
        this.dialogVisible = true;
        this.form.name = row.title;
        this.form.sort = row.content3;
        this.form.treeTitle = `修改目录信息`
        this.form.treeLabel = `目录名称`
        this.form.state=`upd`;
        // this.cascadrValue = row.id
        this.treeIndexDesc = row.name
        this.treeIndex = row.pid;
        if(row.pid === '0') {
          this.cascadrValue = [row.id]
        } else {
          let arr = this.getAllParents(row.pid)
          this.cascadrValue = arr.map(e => e.id)
        }
      },
      onSubmit () {
        if (this.form.name == `` || this.form.name == null) {
          this.$message({
            message: `请输入目录名称！`,
            type: `error`,
          })
          return false;
        }

        const params = {
          'userId': store.getters.user_id.toString(),
          'token': store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          "data": {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryName: this.form.name,
            diretoryParentId: this.treeIndex ? this.treeIndex : this.addRow.id,
            diretoryOrder: this.form.sort,
          },
        }
        if (this.form.state === `add`) {
          let pid = this.cascadrValue[this.cascadrValue.length - 1]
          diretoryParentId: this.treeIndex ? this.treeIndex : this.addRow.id,
          save(params).then((data) => {
            if (data.result === true) {
              this.$message({
                type: `success`,
                message: `操作成功`,
              })
              this.dialogVisible = false;
            }
            else {
              this.$message({
                type: `warning`,
                message: `操作失败`,
              })
            }
          })
        }
        else if (this.form.state === `upd`) {
          const param = {
            'userId': store.getters.user_id.toString(),
            'token': store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            "data": {
              fileDiretoryId: this.updateRow.id,
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryName: this.form.name,
              diretoryParentId: this.treeIndex ? this.treeIndex : this.updateRow.id,
              diretoryOrder: this.form.sort,
            },
          }
          let pid = this.cascadrValue[this.cascadrValue.length - 1]
          diretoryParentId: this.treeIndex ? this.treeIndex : this.updateRow.id,
          update(param).then((data) => {
            if (data.result === true) {
              this.$message({
                type: `success`,
                message: `修改成功`,
              })
              this.dialogVisible = false;
            }
            else {
              this.$message({
                type: `warning`,
                message: `修改失败`,
              })
            }
          })
        }
      },
      cancel () {
        this.dialogVisible = false;
        this.form = {
          id: ``,
          name: ``,
          sort: 0,
          treeTitle: ``,
          treeLabel: ``,
          state: ``,
        }
      },
      handleClose () {
        this.cancel();
      },
    },
  };
</script>

  <style scoped lang="scss">
  .treeBox{
    height: calc(100vh - 124px);
    background: white;
  }
</style>
<style scoped>
.gy-cascader{
  width: auto;
  overflow: scroll;
}
.el-tree {
  min-width: 100%;
  height: calc(100% - 150px);
  display: inline-block;
}
.tree {
  overflow:auto;
  height: 680px;
  min-width: 100%;
}
.demo-drawer__footer .el-button{
    width: 270px;
    height: 35px;
    margin-left: 5px;
    margin-bottom: 10px;
}
</style>
